package com.eeds.start;

import com.arjuna.ats.internal.jdbc.drivers.modifiers.list;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Jacobtest {




    public static void base64ToFile(String base64, String fileName) {
        File file = null;
        //创建文件目录
        String filePath="D:\\image";
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file=new File(filePath+"\\"+fileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 语音转文字并播放
     * 
     * @param
     */
    public static void textToSpeech(String text) {
        ActiveXComponent ax = null;
        try {
            ax = new ActiveXComponent("Sapi.SpVoice");

            // 运行时输出语音内容
            Dispatch spVoice = ax.getObject();
            // 音量 0-100
            ax.setProperty("Volume", new Variant(100));
            // 语音朗读速度 -10 到 +10
            ax.setProperty("Rate", new Variant(1));
            // 执行朗读
            Dispatch.call(spVoice, "Speak", new Variant(text));

            // 下面是构建文件流把生成语音文件

            ax = new ActiveXComponent("Sapi.SpFileStream");
            Dispatch spFileStream = ax.getObject();

            ax = new ActiveXComponent("Sapi.SpAudioFormat");
            Dispatch spAudioFormat = ax.getObject();

            // 设置音频流格式
            Dispatch.put(spAudioFormat, "Type", new Variant(22));
            // 设置文件输出流格式
            Dispatch.putRef(spFileStream, "Format", spAudioFormat);
            // 调用输出 文件流打开方法，创建一个.wav文件
            Dispatch.call(spFileStream, "Open", new Variant("./text.wav"), new Variant(3), new Variant(true));
            // 设置声音对象的音频输出流为输出文件对象
            Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);
            // 设置音量 0到100
            Dispatch.put(spVoice, "Volume", new Variant(100));
            // 设置朗读速度
            Dispatch.put(spVoice, "Rate", new Variant(-2));
            // 开始朗读
            Dispatch.call(spVoice, "Speak", new Variant(text));

            // 关闭输出文件
            Dispatch.call(spFileStream, "Close");
            Dispatch.putRef(spVoice, "AudioOutputStream", null);

            spAudioFormat.safeRelease();
            spFileStream.safeRelease();
            spVoice.safeRelease();
            ax.safeRelease();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void readText(File text) {
        Reader reader=null;
        BufferedReader br=null;
        try {
            reader=new FileReader(text);
            br =new BufferedReader(reader);
            String info="";
            while((info=br.readLine())!=null) {
                textToSpeech(info);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

    public static void main(String[] args) {
        //传入一个txt文本
        //readText(new File("E:/测试.txt"));
        clause(new File("E:/测试.txt"));


    }





    private static final int MIN_THRESHOLD = 50;
    private static final int MAX_THRESHOLD = 80;
    private static List<String> list = new ArrayList<>();

    /**
     * 分句
     * @param file
     */
    public static void clause(File file) {
        String str = null;
        try {

            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), Charset.defaultCharset());
            BufferedReader br = new BufferedReader(isr);

            StringBuffer sb = new StringBuffer(MAX_THRESHOLD);

            while ((str=br.readLine())!=null) {
                //String [] substrs = str.split("。|\\？|\\！|\\?|\\.|!");
                /*正则表达式：句子结束符*/
                String regEx="[。？！?.!]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(str);

                /*按照句子结束符分割句子*/
                String[] substrs = p.split(str);

                /*将句子结束符连接到相应的句子后*/
                if(substrs.length > 0)
                {
                    int count = 0;
                    while(count < substrs.length)
                    {
                        if(m.find())
                        {
                            substrs[count] += m.group();
                        }
                        count++;
                    }
                }
//	              //String [] substrs = str.split("[。？！?.!]");
                for (int i=0;i<substrs.length;i++) {

                    if (substrs[i].length()<MIN_THRESHOLD) {	//语句小于要求的分割粒度
                        sb.append(substrs[i]);
                        //sb.append("||");
                        if (sb.length()>MIN_THRESHOLD) {
                            //System.out.println("A New TU: " + sb.toString());
                            list.add(sb.toString());
                            sb.delete(0, sb.length());
                        }
                    }
                    else {	//语句满足要求的分割粒度
                        if(sb.length()!=0)	//此时如果缓存有内容则应该先将缓存存入再存substrs[i]的内容  以保证原文顺序
                        {
                            list.add(sb.toString());
                            //System.out.println("A New Tu:"+sb.toString());
                            sb.delete(0, sb.length());
                        }
                        list.add(substrs[i]);
                        //System.out.println("A New Tu:"+substrs[i]);
                    }
                }
            }
            br.close();
            isr.close();

            //将分割好的tu放入List中以便传入数据库
            for (Iterator i = list.iterator(); i.hasNext();){
                //System.out.println(i.next());
                textToSpeech(i.next().toString());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}